package com.springapp.mvc.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.springapp.mvc.dm.CRequest;
import com.springapp.mvc.dm.CountListener;
import com.springapp.mvc.dm.Product;
import com.springapp.mvc.dm.User;
import lombok.extern.log4j.Log4j;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by shangdong on 17/4/8.
 */
@Log4j
public class DmConnClient1 {

    private AtomicInteger successCount = new AtomicInteger(0);

    private HttpClient client = null;

    private User user;

    private CountListener listener;

    public static final String loginUrl = "https://auth.dm.de/login";//post

    public static final String tokenUrl = "https://auth.dm.de/oauth/token";//post

    public static final String login468748Url = "https://www.dm.de/login/468748.html";//post

//    public static final String productUrl = "https://www.dm.de/amorelie-basics-gleitgel-mit-geschmack-salted-caramel-p4260458851586.html";


    public HttpClient getClient() {
        return client;
    }

    public void setClient(HttpClient client) {
        this.client = client;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public DmConnClient1() {
        MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
        this.client = new HttpClient(connectionManager);
    }

    public DmConnClient1(CountListener listener) {
        MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
        this.client = new HttpClient(connectionManager);
        this.listener = listener;
    }

    public DmConnClient1(HttpClient client) {
        this.client = client;
    }

    /**
     *   code:4260458851265
     *   tray:false
     *   quantity:10
     *   _CSRFToken:367d6414df2cdff789a5dc214a79d12b //cookie dmctc
     *   asAjax:true
     */
    public static final String addCart = "https://www.dm.de/cart/add/";//post

    /**
     * https://www.dm.de/webflow/468804/checkout.html?execution=e1s1
     * form data :
     *  acceptTermsAndConditions:true
     *  _acceptTermsAndConditions:on
     *  execution:e1s1
     *  _eventId:continue
     *  _CSRFToken:fa36b7e07fde4a51d811c3c8b4590237
     *
     *  https://www.dm.de/cms/de_mcr/webflow/468804/checkout.html?execution=e3s2
     *  deliveryType:HAUPTADRESSE_POSTADRESSE
     *  deliveryModeMainAddress:POS
     *  deliveryAddressId:21848465
     *  deliveryModeShippingAddress:POS
     *  _eventId:submit
     *  _CSRFToken:fa36b7e07fde4a51d811c3c8b4590237
     *
     *  https://www.dm.de/cms/de_mcr/webflow/468804/checkout.html?execution=e3s3
     *  code:Prepayment
     *  execution:e1s3
     *  _eventId:submit
     *  _CSRFToken:fa36b7e07fde4a51d811c3c8b4590237
     *
     *  https://www.dm.de/cms/de_mcr/webflow/468804/checkout.html?execution=e3s4
     *  execution:e1s4
     *  _eventId:continue
     *  _CSRFToken:fa36b7e07fde4a51d811c3c8b4590237
     */
    public static final String checkoutUrl = "https://www.dm.de/webflow/468804/checkout.html";//get response header location

    /**
     * loyaltyCardId:9499930977
     * _CSRFToken:e1e29a38c79bb52bc44e1077b9c788eb
     */
    public static final String addloyaltycard = "https://www.dm.de/cart/addloyaltycard/";// post


//    public static final String productUrl1 = "https://www.dm.de/aptamil-profutura-anfangsmilch-pre-von-geburt-an-p4008976022923.html";


    public static final ExecutorService es = Executors.newCachedThreadPool();

    public static final List<String> productUrls = Lists.newArrayList(
//            "https://www.dm.de/aptamil-profutura-anfangsmilch-pre-von-geburt-an-p4008976022923.html",
            "https://www.dm.de/amorelie-basics-gleitgel-mit-geschmack-salted-caramel-p4260458851586.html",
            "https://www.dm.de/amorelie-basics-2in-1-toy-cleaner-p4260458851272.html",
            "https://www.dm.de/amorelie-basics-gleitgel-neutral-wasserbasiert-p4260458851265.html"
    );

    public static void main(String[] args) {
        DmConnClient1 client =  new DmConnClient1();
        client.login("jiangweizheng12+37@gmail.com", "123456789");
//        boolean b = client.addProductToCart(productUrl1);
//        client.addMultiProductToCart1(productUrls);
//        client.pay();
    }

    public static void executeNewUser(User user,List<Product> products){
        DmConnClient1 client =  new DmConnClient1();
        client.login(user.getUsername(), user.getPassword());
//        boolean b = client.addProductToCart(productUrl1);
        client.addMultiProductToCart1(products);
    }

//    es.execute(new Runnable() {
//        @Override
//        public void run() {
//            int all = stringFutureMap.size();
//            while (true) {
//                for (Future<Boolean> booleanFuture : stringFutureMap.values()) {
//                    try {
//                        if (booleanFuture.get(100,TimeUnit.MILLISECONDS)){
//                            all --;
//                        }
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    } catch (ExecutionException e) {
//                        e.printStackTrace();
//                    } catch (TimeoutException e) {
//
//                    }
//                }
//                if (all == 0){
//                    break;
//                }
//            }
//    });


    public void login(String username,String password){
        String referer = doLoginPost(username, password);
        String code = getLoginCode(referer);
        String access_token = getTokenPost(referer, code);
        doLogin468748Post(access_token, referer);
    }



    public void addMultiProductToCart1(List<Product> products) {
        Map<String,Future<String>> map = Maps.newHashMap();
        for (Product product : products) {
            Future<String> submit = es.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    while (true){
                        Thread.currentThread().sleep(50);
                        String count = getCount(product.getProductUrl());
                        int countInt = parseInt(count);
                        if (StringUtils.isNotBlank(count) && countInt > 0){
                            if (countInt >= product.getBuyCount()){
                                return String.valueOf(product.getBuyCount());
                            }else {
                                return count;
                            }
                        }
                    }
                }
            });
            map.put(product.getProductUrl(),submit);
        }
        es.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        int addCartSuccessCount = map.size();
                        for (Map.Entry<String, Future<String>> stringFutureEntry : map.entrySet()) {
                            String url = stringFutureEntry.getKey();
                            Future<String> countFuture = stringFutureEntry.getValue();
                            String productCode = getProductCode(url);
                            if (countFuture.isDone()) {
                                String count = countFuture.get();
                                String s = addCart(productCode, count, url);
                                if (s != null) {
                                    addCartSuccessCount--;
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        es.execute(new Runnable() {
            @Override
            public void run() {
                int swich = 0;
                while (true) {
                    int cartCount = getCartCount();
                    if (swich == 0 && cartCount <= 0) {
                        try {
                            Thread.currentThread().sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (cartCount > 0) {
                        swich++;
                        pay();
                    }
//                    try {
//                        Thread.currentThread().sleep(500);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                }
            }
        });
        es.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        Thread.currentThread().sleep(30000);
                        System.out.println("total success count = " + successCount.get());
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    public void addCartAndPay(String count,Product product,String user){
        String productCode = getProductCode(product.getProductUrl());
        addCart(productCode, count, product.getProductUrl());
        pay(user);

    }


    public void addMultiProductToCart2(List<Product> products,User user) {
        Map<String,Future<String>> map = Maps.newHashMap();
        DmConnClient1 dmConnClient = this;
        for (Product product : products) {
            Future<String> submit = es.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    while (true){
                        Thread.currentThread().sleep(50);
                        String count = getCount(product.getProductUrl());
                        int countInt = parseInt(count);
                        if (StringUtils.isNotBlank(count) && countInt > 0){
                            if (countInt >= product.getBuyCount()){
                                return String.valueOf(product.getBuyCount());
                            }else {
//                                listener.hasCount(count,dmConnClient,user,products);
                                return count;
                            }
                        }
                    }
                }
            });
            map.put(product.getProductUrl(),submit);
        }
        es.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        int addCartSuccessCount = map.size();
                        for (Map.Entry<String, Future<String>> stringFutureEntry : map.entrySet()) {
                            String url = stringFutureEntry.getKey();
                            Future<String> countFuture = stringFutureEntry.getValue();
                            String productCode = getProductCode(url);
                            if (countFuture.isDone()) {
                                String count = countFuture.get();
                                String s = addCart(productCode, count, url);
                                if (s != null) {
                                    addCartSuccessCount--;
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        es.execute(new Runnable() {
            @Override
            public void run() {
                int swich = 0;
                while (true) {
                    int cartCount = getCartCount();
                    if (swich == 0 && cartCount <= 0) {
                        try {
                            Thread.currentThread().sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (cartCount > 0) {
                        swich++;
                        pay();
                    }
//                    try {
//                        Thread.currentThread().sleep(500);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                }
            }
        });
        es.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        Thread.currentThread().sleep(30000);
                        System.out.println("total success count = " + successCount.get());
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    public Map<String,Future<Boolean>> addMultiProductToCart(List<String> productUrls) {
        Map<String,Future<Boolean>> map = Maps.newHashMap();
        for (String url : productUrls) {
            Future<Boolean> submit = es.submit(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    boolean b = addProductToCart(url);
                    if (b == false) {
                        while (true) {
                            boolean b1 = addProductToCart(url);
                            if (b1) break;
                        }
                    }
                    return true;
                }
            });
            map.put(url, submit);
        }
        return map;

    }



    public boolean addProductToCart(String productUrl){
        String count = getCount(productUrl);
        if (StringUtils.isBlank(count)){
            return false;
        }
        count = "1";
        //todo 购买个数
//        int count1 = parseInt(count);

        String productCode = getProductCode(productUrl);
        String s = addCart(productCode, count, productUrl);
        if (s != null){
            return true;
        }
        return false;
    }

    public static int parseInt(String count) {
        try {
            return Integer.parseInt(count);
        }catch (Exception e){
            System.out.println("count isn't number! count = " + count);
            return 0;
        }
    }

    public void pay(String user){
        try {
            addloyaltycard(getCSRFToken());
            String checkout = checkout();
            String s = checkout1(checkout);
            if (StringUtils.isBlank(s)){
                System.out.println("checkout1 error!response is null!");
            }
            String deliveryAddressID = getDeliveryAddressID(s);
            String s1 = checkout2(s, deliveryAddressID);
            if (StringUtils.isBlank(s1)){
                System.out.println("checkout1 error!response is null!");
            }
            String s2 = checkout3(s1);
            if (StringUtils.isBlank(s2)){
                System.out.println("checkout1 error!response is null!");
            }
            String s3 = checkout4(s2);
            if ("success".equals(s3)){
                System.out.println(user +" : 下单成功！");
            }
        }catch (Throwable e){
            e.printStackTrace();
        }
    }

    public void pay(){
        try {
            addloyaltycard(getCSRFToken());
            String checkout = checkout();
            String s = checkout1(checkout);
            if (StringUtils.isBlank(s)){
                System.out.println("checkout1 error!response is null!");
            }
            String deliveryAddressID = getDeliveryAddressID(s);
            String s1 = checkout2(s, deliveryAddressID);
            if (StringUtils.isBlank(s1)){
                System.out.println("checkout1 error!response is null!");
            }
            String s2 = checkout3(s1);
            if (StringUtils.isBlank(s2)){
                System.out.println("checkout1 error!response is null!");
            }
            String s3 = checkout4(s2);
        }catch (Throwable e){
            e.printStackTrace();
        }
    }

    private String getDeliveryAddressID(String url) {
        String s = doGet(url);
        Document parse = Jsoup.parse(s);
        Element mainAddressId1 = parse.getElementById("mainAddressId1");
        String deliveryAddressID = mainAddressId1.attr("value");
        System.out.println("deliveryAddressID == "+deliveryAddressID);
        return deliveryAddressID;
    }

    public static String getLoginCode(String url){
        String[] split = url.split("\\?");
        String[] split1 = split[1].split("=");
        System.out.println(split1[1]);
        return split1[1];
    }

    public String doLoginPost(String username,String password){
        PostMethod post = null;
        try {
            post = new PostMethod(loginUrl);
            post.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            post.setRequestHeader("Host","auth.dm.de");
            post.setRequestHeader("Origin","https://www.dm.de");
            NameValuePair signNV = new NameValuePair("username", username);
            NameValuePair signNV1 = new NameValuePair("password", password);
            NameValuePair signNV2 = new NameValuePair("auth_url", "%2Foauth%2Fauthorize%3Fclient_id%3Ddm-de%26redirect_uri%3Dhttps%3A%2F%2Fwww.dm.de%2Flogin%2F468748.html%26response_type%3Dcode");
            post.setRequestBody(new NameValuePair[]{signNV,signNV1,signNV2});
            client.executeMethod(post);
            //打印服务器返回的状态
            if (post.getStatusCode() == 302) {//请求不成功
                String location = post.getResponseHeader("Location").getValue();
                System.out.println(location);
                return location;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放连接
            if (post != null) {
                post.releaseConnection();
            }
        }
        return null;
    }


    public String getTokenPost(String referer,String code){
        PostMethod post = null;
        try {
            post = new PostMethod(tokenUrl);
            post.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            post.setRequestHeader("Host","auth.dm.de");
            post.setRequestHeader("Origin","https://www.dm.de");
            post.setRequestHeader("Referer",referer);
            NameValuePair signNV = new NameValuePair("grant_type", "authorization_code");
            NameValuePair signNV1 = new NameValuePair("client_id", "dm-de");
            NameValuePair signNV2 = new NameValuePair("code", code);
            NameValuePair signNV3 = new NameValuePair("redirect_uri", "https://www.dm.de/login/468748.html");

            post.setRequestBody(new NameValuePair[]{signNV,signNV1,signNV2,signNV3});
            client.executeMethod(post);
            //打印服务器返回的状态
            if (post.getStatusCode() == 200) {//请求不成功
//                String location = post.getResponseHeader("Location").getValue();
                String responseBodyAsString = post.getResponseBodyAsString();
                System.out.println(responseBodyAsString);
                JSONObject jsonObject = JSON.parseObject(responseBodyAsString);
                String access_token = jsonObject.getString("access_token");
//                System.out.println(location);
                return access_token;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放连接
            if (post != null) {
                post.releaseConnection();
            }
        }
        return null;
    }

    public String doLogin468748Post(String access_token,String referer){
        PostMethod post = null;
        try {
            post = new PostMethod(login468748Url);
            post.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            post.setRequestHeader("Host","auth.dm.de");
            post.setRequestHeader("Origin","https://www.dm.de");
            post.setRequestHeader("Referer", referer);
            NameValuePair signNV = new NameValuePair("access_token", access_token);
            post.setRequestBody(new NameValuePair[]{signNV});
            client.executeMethod(post);
            //打印服务器返回的状态
            if (post.getStatusCode() == 302) {
                String location = post.getResponseHeader("Location").getValue();
                System.out.println(location);
                return location;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放连接
            if (post != null) {
                post.releaseConnection();
            }
        }
        return null;
    }


    public String doGet(String url) {
        HttpMethod method = null;
        try {
            // 设置代理服务器地址和端口
            //client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);
            // 使用 GET 方法 ，如果服务器需要通过 HTTPS 连接，那只需要将下面 URL 中的 http 换成 https
            method = new GetMethod(url);
            long l = System.currentTimeMillis();

            client.executeMethod(method);
            long l1 = System.currentTimeMillis();
            System.out.println("doget execute = " + (l1 - l));
            //打印服务器返回的状态
//            System.out.println(method.getStatusLine());
            if (method.getStatusCode() != 200) {//请求不成功
                System.out.println("请求失败！ " + method.getStatusLine());
            }
            //打印返回的信息
//            System.out.println(method.getResponseBodyAsString());
            InputStream responseBodyAsStream = method.getResponseBodyAsStream();

            return method.getResponseBodyAsString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放连接
            if (method != null) {
                method.releaseConnection();
            }
        }
        return null;
    }

    public String getProductCode(String productUrl){
//           https://www.dm.de/amorelie-basics-gleitgel-mit-geschmack-salted-caramel-p4260458851586.html
        String[] split = productUrl.split("-");
        String[] split1 = split[split.length - 1].split("\\.");
        String numbers = getNumbers(split1[0]);
//        System.out.println("productcode = "+ numbers);
        return numbers;
    }

    public static String getNumbers(String content) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }

    public String getCount(String productUrl){
        try{
            String s = doGet(productUrl);
            Document parse = Jsoup.parse(s);
            Elements elementsByClass = parse.body().getElementsByClass("product-attributes-cart-amount");
            Elements select = elementsByClass.get(0).getElementsByTag("select");
            Elements options = select.get(0).children();
            String count = options.last().attr("value");
            System.out.println("product count = "+count);
            return count;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public List<Integer> getCanChooseCount(String productUrl){
        List<Integer> canChooseCount = Lists.newArrayList();
        try{
//            long l = System.currentTimeMillis();
//            String s = doGet(productUrl);
            Connection.Response execute = Jsoup.connect(productUrl).execute();
            String s = execute.body();
//            long l1 = System.currentTimeMillis();
//            System.out.println("doGet = " + (l1 - l));

            Document parse = Jsoup.parse(s);
            Elements elementsByClass = parse.body().getElementsByClass("product-attributes-cart-amount");
            Elements select = elementsByClass.get(0).getElementsByTag("select");
            Elements options = select.get(0).children();
            for (Element option : options) {
                String count = option.attr("value");
                if (StringUtils.isNotBlank(count)){
                    canChooseCount.add(parseInt(count));
                }
            }
//            long l2 = System.currentTimeMillis();
//            System.out.println("other =" +(l2-l1));
//            System.out.println("product count = "+count);
            return canChooseCount;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public String getCSRFToken(){
        Cookie[] cookies = client.getState().getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("dmctc")){
                return cookie.getValue();
            }
        }
        System.out.println("get getCSRFToken error!");
        return "";
    }

    public String addCart(String code,String quantity,String referer){
        PostMethod post = null;
        try {
            post = new PostMethod(addCart);
            post.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            post.setRequestHeader("Host","auth.dm.de");
            post.setRequestHeader("Origin","https://www.dm.de");
            post.setRequestHeader("Referer",referer);
            NameValuePair signNV = new NameValuePair("code", code);
            NameValuePair signNV1 = new NameValuePair("tray", "false");
            NameValuePair signNV2 = new NameValuePair("quantity", quantity);
            NameValuePair signNV3 = new NameValuePair("_CSRFToken", getCSRFToken());
            NameValuePair signNV4 = new NameValuePair("asAjax", "true");

            post.setRequestBody(new NameValuePair[]{signNV, signNV1, signNV2, signNV3, signNV4});
            client.executeMethod(post);
            //打印服务器返回的状态
            System.out.println("add cart code = " + post.getStatusCode());
            if (post.getStatusCode() == 200) {//请求不成功
//                String location = post.getResponseHeader("Location").getValue();
                String responseBodyAsString = post.getResponseBodyAsString();
                if (responseBodyAsString.contains("error!")){
                    return null;
                }
                System.out.println("add cart resp = " + responseBodyAsString);
                return responseBodyAsString;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放连接
            if (post != null) {
                post.releaseConnection();
            }
        }
        return null;
    }

    public String addloyaltycard(String _CSRFToken){
        PostMethod post = null;
        try {
            post = new PostMethod(addloyaltycard);
            post.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            post.setRequestHeader("Host","auth.dm.de");
            post.setRequestHeader("Origin", "https://www.dm.de");
//            post.setRequestHeader("Referer",referer);
            NameValuePair signNV = new NameValuePair("loyaltyCardId", "e1e29a38c79bb52bc44e1077b9c788eb");
            NameValuePair signNV1 = new NameValuePair("_CSRFToken", _CSRFToken);

            post.setRequestBody(new NameValuePair[]{signNV, signNV1});
            client.executeMethod(post);
            //打印服务器返回的状态
            if (post.getStatusCode() == 200) {//请求不成功
//                String location = post.getResponseHeader("Location").getValue();
                String responseBodyAsString = post.getResponseBodyAsString();
                System.out.println("addloyaltycard = "+ responseBodyAsString);
                return responseBodyAsString;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放连接
            if (post != null) {
                post.releaseConnection();
            }
        }
        return null;
    }

    public String checkout(){
        HttpMethod method = null;
        try {
            // 设置代理服务器地址和端口
            //client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);
            // 使用 GET 方法 ，如果服务器需要通过 HTTPS 连接，那只需要将下面 URL 中的 http 换成 https
            method = new GetMethod(checkoutUrl);
            client.executeMethod(method);
            //打印服务器返回的状态
//            System.out.println(method.getStatusLine());
            if (method.getStatusCode() == 302) {//请求不成功
                String location1 = method.getResponseHeader("Location").getValue();
                System.out.println("checkout =" + location1);
                return location1;
            }
            if (method.getStatusCode() == 200){
                String queryString = method.getQueryString();
                return checkoutUrl + "?" + queryString;
            }
            //打印返回的信息
//            System.out.println(method.getResponseBodyAsString());
            return method.getResponseBodyAsString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放连接
            if (method != null) {
                method.releaseConnection();
            }
        }
        return null;
    }

    public String checkout1(String url){
        PostMethod post = null;
        try {
            String checkoutPostUrl = getCheckoutPostUrl(url);
            post = new PostMethod(checkoutPostUrl);
            Map<String, String> map = CRequest.URLRequest(checkoutPostUrl);
            post.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            post.setRequestHeader("Host","auth.dm.de");
            post.setRequestHeader("Origin", "https://www.dm.de");
//            post.setRequestHeader("Referer",referer);
            NameValuePair signNV = new NameValuePair("acceptTermsAndConditions", "true");
            NameValuePair signNV1 = new NameValuePair("_acceptTermsAndConditions", "on");
            NameValuePair signNV2 = new NameValuePair("execution", map.get("execution"));
            NameValuePair signNV3 = new NameValuePair("_eventId", "continue");
            NameValuePair signNV4 = new NameValuePair("_CSRFToken", getCSRFToken());

            post.setRequestBody(new NameValuePair[]{signNV,signNV1,signNV2,signNV3,signNV4});
            client.executeMethod(post);
            //打印服务器返回的状态
            if (post.getStatusCode() == 302) {//请求不成功
                String responseBodyAsString = post.getResponseHeader("Location").getValue();
                System.out.println("checkout1 = " + responseBodyAsString);
                return responseBodyAsString;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放连接
            if (post != null) {
                post.releaseConnection();
            }
        }
        return null;
    }

    /**
     *
     * @param url
     * @param deliveryAddressId //todo需获取
     * @return
     */
    public String checkout2(String url,String deliveryAddressId){
        PostMethod post = null;
        try {
            String checkoutPostUrl = getCheckoutPostUrl(url);
            post = new PostMethod(checkoutPostUrl);
//            Map<String, String> map = CRequest.URLRequest(checkoutPostUrl);
            post.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            post.setRequestHeader("Host","auth.dm.de");
            post.setRequestHeader("Origin", "https://www.dm.de");
//            post.setRequestHeader("Referer",referer);
            NameValuePair signNV = new NameValuePair("deliveryType", "HAUPTADRESSE_POSTADRESSE");
            NameValuePair signNV1 = new NameValuePair("deliveryModeMainAddress", "POS");
            NameValuePair signNV2 = new NameValuePair("deliveryAddressId", deliveryAddressId == null ? "21848465" : deliveryAddressId);
            NameValuePair signNV3 = new NameValuePair("deliveryModeShippingAddress", "POS");
            NameValuePair signNV4 = new NameValuePair("_eventId", "submit");
            NameValuePair signNV5 = new NameValuePair("_CSRFToken", getCSRFToken());

            post.setRequestBody(new NameValuePair[]{signNV,signNV1,signNV2,signNV3,signNV4,signNV5});
            client.executeMethod(post);
            //打印服务器返回的状态
            if (post.getStatusCode() == 302) {//请求不成功
                String responseBodyAsString = post.getResponseHeader("Location").getValue();
                System.out.println("checkout2 = " + responseBodyAsString);
                return responseBodyAsString;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放连接
            if (post != null) {
                post.releaseConnection();
            }
        }
        return null;
    }


    public String checkout3(String url){
        PostMethod post = null;
        try {
            String checkoutPostUrl = getCheckoutPostUrl(url);
            post = new PostMethod(checkoutPostUrl);
            Map<String, String> map = CRequest.URLRequest(checkoutPostUrl);
            post.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            post.setRequestHeader("Host","auth.dm.de");
            post.setRequestHeader("Origin", "https://www.dm.de");
//            post.setRequestHeader("Referer",referer);
            NameValuePair signNV = new NameValuePair("code", "Prepayment");
            NameValuePair signNV1 = new NameValuePair("execution", map.get("execution"));
            NameValuePair signNV2 = new NameValuePair("_eventId", "submit");
            NameValuePair signNV3 = new NameValuePair("_CSRFToken", getCSRFToken());

            post.setRequestBody(new NameValuePair[]{signNV,signNV1,signNV2,signNV3});
            client.executeMethod(post);
            //打印服务器返回的状态
            if (post.getStatusCode() == 302) {//请求不成功
                String responseBodyAsString = post.getResponseHeader("Location").getValue();
                System.out.println("checkout3 = " + responseBodyAsString);
                return responseBodyAsString;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放连接
            if (post != null) {
                post.releaseConnection();
            }
        }
        return null;
    }

    public String checkout4(String url){
        PostMethod post = null;
        try {
            String checkoutPostUrl = getCheckoutPostUrl(url);
            post = new PostMethod(checkoutPostUrl);
            Map<String, String> map = CRequest.URLRequest(checkoutPostUrl);
            post.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            post.setRequestHeader("Host","auth.dm.de");
            post.setRequestHeader("Origin", "https://www.dm.de");
//            post.setRequestHeader("Referer",referer);
            NameValuePair signNV1 = new NameValuePair("execution", map.get("execution"));
            NameValuePair signNV2 = new NameValuePair("_eventId", "continue");
            NameValuePair signNV3 = new NameValuePair("_CSRFToken", getCSRFToken());

            post.setRequestBody(new NameValuePair[]{signNV1,signNV2,signNV3});
            client.executeMethod(post);
            successCount.incrementAndGet();
//            System.out.println("total successCount = " + i);
            //打印服务器返回的状态
            if (post.getStatusCode() == 302) {//请求不成功
                String responseBodyAsString = post.getResponseHeader("Location").getValue();
                System.out.println("checkout4 = " + responseBodyAsString);
                return responseBodyAsString;
            }
            if (post.getStatusCode() == 200){
                System.out.println("下单成功！");
                return "success";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //释放连接
            if (post != null) {
                post.releaseConnection();
            }
        }
        return null;
    }

    public int getCartCount(){
        String url = "https://www.dm.de/cart?view=asWidget";
        try{
            String s = doGet(url);
            Document parse = Jsoup.parse(s);
            Elements elementsByClass = parse.getElementsByClass("comp-minicart-header");
            Element span = elementsByClass.get(0).getElementsByTag("span").get(0);
            String text = span.text();
            String numbers = getNumbers(text);
            int totalProductCount = parseInt(numbers);
            System.out.println("cart count = " + totalProductCount);
            return totalProductCount;
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }


    public static String getCheckoutPostUrl(String url){
        System.out.println(url);
        String regex = "https://www.dm.de";
        String[] a  = url.split(regex);
        return regex + "/cms/de_mcr" + a[1];
    }

    public boolean isLogged(){
        try{
            Cookie[] cookies = client.getState().getCookies();
            for (Cookie cookie : cookies) {
                if ("isLoggedIn".equals(cookie.getName())){
                    if ("true".equals(cookie.getValue())){
                        return true;
                    }
                }
            }
            return false;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

}
